package com.harbour.mmall.util;



import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 上传文件对象
 *
 * @author pc
 */
public class UploadHtmlUtil {
    /**
     * 初始化变量
     */
    private static String CONTENT_TYPE = "multipart/form-data", CHARSET = "utf-8", uploadUrl, PREFIX = "---------------------------", LINE_END = "\r\n";

    static {
        uploadUrl = "http://test.pms.harbourhome.com.cn/UploadAllObjectServlet?server=upload";
    }

    private static final int TIME_OUT = 30 * 1000; // 超时时间

    public static final String APPLICATION_TYPE_PDF = "pdf";

    private static final String DEFAULT_APPLICATION_TYPE = "octet-stream";

    /**
     * 上传文件到服务器
     *
     * @param file 需要上传的文件
     *             请求的rul
     * @return 返回响应的内容
     */
    public static String uploadFile(File file, String applicationType) {
        String res = "";
        long BOUNDARY = System.currentTimeMillis(); // 边界标识 随机生成

        // String PREFIX = "-----------------------------192671317912921",开始
        // String PREFIX = "-----------------------------192671317912921--",结束
        URL url = null;
        HttpURLConnection conn = null;
        try {
            url = new URL(uploadUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(true); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + PREFIX + BOUNDARY);
            if (file != null) {
                /**
                 * 当文件不为空时执行上传
                 */
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名
                 */
                sb.append("Content-Disposition: form-data; name=\"file1\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/" + (StringUtils.isBlank(applicationType) ? DEFAULT_APPLICATION_TYPE : applicationType));
                sb.append(LINE_END + LINE_END);
                dos.write(sb.toString().getBytes());
                sb.delete(0, sb.length());
                sb = null;
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + "--" + BOUNDARY + "--").getBytes();
                dos.write(end_data);
                dos.flush();
                dos.close();
                conn.connect();
                InputStream inputStream = conn.getInputStream();
                /**
                 * 获取响应码 200=成功 当响应成功，获取响应的流
                 */
                if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                    res = getResponseForBuffer(inputStream);
                    inputStream.close();
                } else {
                    res = "{\"success\":false}";
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != conn) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }

    /**
     * 解析成字符串
     *
     * @param inputStream
     * @return
     */
    private static String getResponseForBuffer(InputStream inputStream) {
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer buffer = new StringBuffer();
        String data;
        try {
            while ((data = br.readLine()) != null) {
                buffer.append(data);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
//        boolean flag = saveUrlAs("http://fangqian.oss-cn-beijing.aliyuncs.com/_6dc31981-fb62-43dd-b046-9bce0b303555_b.png", "f://111.png");
//        //String con = uploadFile(new File("f://111.png"), null);
//        String con1 = uploadFile(new File("D:\\IdeaProject\\wl-pms\\src\\main\\java\\com\\odfly\\common\\temp\\barcode\\5b509fb3-f5f3-48dd-8dec-c0c1d71865ee.png"), null);
//        JsonObject jsonObject = JsonObject.fromObject(con1);
//
//        System.out.println(jsonObject.getString("url"));
    }

    public static String upfile(String path) {
        String con = uploadFile(new File(path), null);
        return con;
    }

    public static String upfile(String path, String applicationType) {
        String con = uploadFile(new File(path), applicationType);
        return con;
    }

    public static boolean saveUrlAs(String photoUrl, String fileName) {
        //此方法只能用户HTTP协议
        try {
            URL url = new URL(photoUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            DataInputStream in = new DataInputStream(connection.getInputStream());
            DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
